import mongoose from 'mongoose'

export const databaseConfig = {
  // MongoDB配置
  mongodb: {
    url: process.env.MONGODB_URI || 'mongodb://localhost:27017/livechat',
    options: {
      useNewUrlParser: true,
      useUnifiedTopology: true,
      useCreateIndex: true,
      useFindAndModify: false,
      // 连接池配置
      poolSize: 10,
      // 超时设置
      connectTimeoutMS: 10000,
      socketTimeoutMS: 45000,
      // 重试设置
      retryWrites: true,
      retryReads: true,
      // 心跳检测
      heartbeatFrequencyMS: 10000,
      // 副本集设置
      replicaSet: process.env.MONGODB_REPLICA_SET,
      // 身份验证
      auth: {
        username: process.env.MONGODB_USER,
        password: process.env.MONGODB_PASS,
      },
    },
  },

  // Redis配置
  redis: {
    // 主连接
    master: {
      host: process.env.REDIS_HOST || 'localhost',
      port: parseInt(process.env.REDIS_PORT || '6379'),
      password: process.env.REDIS_PASSWORD,
      db: parseInt(process.env.REDIS_DB || '0'),
      // 连接设置
      connectTimeout: 10000,
      maxRetriesPerRequest: 3,
      enableReadyCheck: true,
      // 自动重连
      retryStrategy(times: number) {
        const delay = Math.min(times * 50, 2000)
        return delay
      },
    },
    // 从连接（可选）
    slave: {
      host: process.env.REDIS_SLAVE_HOST,
      port: parseInt(process.env.REDIS_SLAVE_PORT || '6379'),
      password: process.env.REDIS_SLAVE_PASSWORD,
      db: parseInt(process.env.REDIS_SLAVE_DB || '0'),
    },
    // 缓存配置
    cache: {
      // 通用缓存
      common: {
        ttl: 3600, // 1小时
        maxSize: 1000, // 最大缓存条目
      },
      // 房间信息缓存
      room: {
        ttl: 300, // 5分钟
        maxSize: 500,
      },
      // 用户信息缓存
      user: {
        ttl: 1800, // 30分钟
        maxSize: 1000,
      },
    },
    // 限流配置
    rateLimits: {
      chat: {
        points: 10, // 令牌数
        duration: 60, // 时间窗口(秒)
      },
      api: {
        points: 100,
        duration: 60,
      },
    },
  },

  // 备份配置
  backup: {
    enabled: true,
    schedule: '0 2 * * *', // 每天凌晨2点
    keepDays: 7, // 保留7天
    path: 'D:\\backups', // Windows路径格式
    compress: true,
  },

  // 监控配置
  monitor: {
    enabled: true,
    interval: 60000, // 监控间隔(毫秒)
    thresholds: {
      cpu: 80, // CPU使用率告警阈值
      memory: 80, // 内存使用率告警阈值
      disk: 85, // 磁盘使用率告警阈值
      connections: 1000, // 最大连接数告警阈值
    },
    notification: {
      email: process.env.ADMIN_EMAIL,
      phone: process.env.ADMIN_PHONE,
    },
  },
}

export const connectDB = async () => {
  try {
    let retries = 5
    while (retries > 0) {
      try {
        await mongoose.connect(databaseConfig.mongodb.url, databaseConfig.mongodb.options)
        console.log('MongoDB connected successfully')
        return true
      } catch (error) {
        retries -= 1
        if (retries === 0) throw error
        console.log(`Failed to connect to MongoDB. Retrying... (${retries} attempts left)`)
        await new Promise((resolve) => setTimeout(resolve, 3000))
      }
    }
    return false
  } catch (error) {
    console.error('MongoDB connection error:', error)
    return false
  }
}
